package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.Excel.ExcelUtil;
import com.jsbj.Excel.ReadXSSExcelUtil;
import com.jsbj.base.ResultBean;
import com.jsbj.base.WXConstant;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.sms.YunMiSms;
import com.jsbj.tools.*;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysUserMapper;
import com.jsbj.user.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统登录用户表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-02-21
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysRegisterUserService sysRegisterUserService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysUserOrgService sysUserOrgService;

    @Autowired
    private ISysRoleUserService sysRoleUserService;

    @Autowired
    private ISysOrgService sysOrgService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysRoleTenantService sysRoleTenantService;

    @Autowired
    private ISysUserPostService sysUserPostService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;
    @Autowired
    private ISysProjectService sysProjectService;

    @Override
    public SysUser queryByLoginId(String loginId) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysUser::getLoginId, loginId);
        wrapper.eq(SysUser::getDisabled, 0);
        wrapper.last(" limit 1 ");
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public ResultBean<Object> registerUser(JSONObject object) {
        ResultBean ret = new ResultBean();

        String loginId = object.getString("loginId");
        String userName = object.getString("userName");
        String password = object.getString("password");
        // 账号密码不能为空
        if (StringUtils.isEmpty(loginId) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return ret.build("账号密码不能为空");
        }
        // 账号只能为手机号
        String regex="^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\\d{8}$";
        Pattern pattern=Pattern.compile(regex); //编译正则表达式
        Matcher matcher=pattern.matcher(loginId); //创建给定输入模式的匹配器
        boolean bool = matcher.matches();
        if (!bool) {
            return ret.build("账号只能为手机号！");
        }
        // 账号已存在
        if (null != this.queryByLoginId(loginId)) {
            return ret.build("账号已存在，请直接登录！");
        }
        // 开始保存
        SysUser sysUser = new SysUser();
        sysUser.setLoginId(loginId);
        sysUser.setUserName(userName);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(passwordEncoder.encode(password));
        sysUser.setPwdDomainCode(password);
        sysUser.setMobile(loginId);
        sysUser.setRegisterSource(2);
        sysUser.setUserState(2);
        sysUser.setDisabled(0);
        sysUser.setCreaterId("1");
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateId("1");
        sysUser.setUpdateTime(new Date());
        baseMapper.insert(sysUser);
        return ret.success("处理成功！");
    }

    @Override
    public ResultBean sendMess(String phoneNumber, String sign) {
        ResultBean ret = new ResultBean();
        int message = RandomUtils.NextInt(100000, 999999);
        String content = "您好,本次登录验证码为:" + message + "，10分钟内输入有效";
        // 发送短信验证码
        try {
            if(StringUtils.isEmpty(sign)){
                sign = "智慧工地";
            }
            Map<String, String> result = YunMiSms.sendSms(phoneNumber, content, "【"+sign+"】");
            if ("true".equals(MapUtils.getString(result, "flag"))) {
                //保存生成的验证码
                int code = sysRegisterUserService.updateMessage(phoneNumber, String.valueOf(message));
                return ret.success("发送成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.build("发送失败");
    }

    @Override
    public ResultBean checkMessage(String phoneNumber, String message) {
        return sysRegisterUserService.checkMessage(phoneNumber, message);
    }

    @Override
    public void updateEquipmentId(String uid, String equipmentId, String equipmentType) {
        SysUser sysUser = baseMapper.selectById(uid);
        sysUser.setEquipmentId(equipmentId);
        sysUser.setEquipmentType(equipmentType);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
    }

    @Override
    public ResultBean<Object> updatePassword(JSONObject object) {
        ResultBean ret = new ResultBean();
        String loginId = object.getString("loginId");
        String password = object.getString("password");
        String passwordRepeat = object.getString("passwordRepeat");

        if (StringUtils.isEmpty(loginId) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            ret.build("必填项不能为空！");
        } else if (!password.equals(passwordRepeat)) {
            ret.build("密码不一致！");
        } else {
            // 更新密码
            SysUser sysUser = this.queryByLoginId(loginId);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPassword(passwordEncoder.encode(password));
            sysUser.setPwdDomainCode(password);
            baseMapper.updateById(sysUser);
            ret.success("处理成功！");
        }
        return ret;
    }

    @Override
    public List<Map<String, Object>> getUsersByTenantCode(String tenantCode) {
        return baseMapper.getUsersByTenantCode(tenantCode);
    }

    @Override
    public SysUser getUserByTenantCode(String tenantCode) {
        SysTenant sysTenant = sysTenantService.getByTenantCode(tenantCode);
        if (null != sysTenant) {
            String account = sysTenant.getTenantSuperAccount();
            SysUser sysUser = this.queryByLoginId(account);
            if (null == sysUser) {
                sysUser = baseMapper.selectById(account);
            }
            return sysUser;
        }
        return null;
    }

    @Override
    public ResultBean<String> add(SysUser sysUser) throws Exception {
        String userId = RequestHeaderUtils.getUserId(request);
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysUser::getLoginId, sysUser.getLoginId());
        qw.eq(SysUser::getDisabled, 0);
        List<SysUser> sysUsers = baseMapper.selectList(qw);
        if (null == sysUser.getId()) {
            if (CollectionUtils.isNotEmpty(sysUsers)) {
                return new ResultBean<>().build("登陆账号已存在，请重新添加！");
            }
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPwdDomainCode(sysUser.getPassword());
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            sysUser.setCreaterId(userId);
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateId(userId);
            sysUser.setUpdateTime(new Date());
            baseMapper.insert(sysUser);
            //新增用户组织关联表
            if(StringUtils.isNotEmpty(sysUser.getOrgId())){
                SysUserOrg sysUserOrg = new SysUserOrg();
                sysUserOrg.setOrgId(sysUser.getOrgId());
                sysUserOrg.setUserId(sysUser.getId());
                sysUserOrg.setCreaterId(sysUser.getCreaterId());
                sysUserOrg.setCreateTime(new Date());
                sysUserOrg.setUpdateId(sysUser.getUpdateId());
                sysUserOrg.setUpdateTime(new Date());
                sysUserOrgService.save(sysUserOrg);
            }

            //新增用户岗位关联表
            if(StringUtils.isNotEmpty(sysUser.getPostId())){
                SysUserPost sysUserPost = new SysUserPost();
                sysUserPost.setPostId(sysUser.getPostId());
                sysUserPost.setUserId(sysUser.getId());
                sysUserPost.setCreaterId(sysUser.getCreaterId());
                sysUserPost.setCreateTime(new Date());
                sysUserPost.setUpdateId(sysUser.getUpdateId());
                sysUserPost.setUpdateTime(new Date());
                sysUserPost.setTenantCode(sysUser.getTenantCode());
                sysUserPostService.save(sysUserPost);
            }
            if (StringUtils.isNotEmpty(sysUser.getRoleId())) {
                String[] roleIdArr = sysUser.getRoleId().split(",");
                for (String roleId : roleIdArr) {
                    SysRoleUser sysRoleUser = new SysRoleUser();
                    sysRoleUser.setRoleId(roleId);
                    sysRoleUser.setUserId(sysUser.getId());
                    sysRoleUser.setCreaterId(userId);
                    sysRoleUser.setCreateTime(new Date());
                    sysRoleUser.setUpdateId(userId);
                    sysRoleUser.setUpdateTime(new Date());
                    sysRoleUserService.save(sysRoleUser);
                }
            }


        } else {
            SysUser sysUser1 = baseMapper.selectById(sysUser.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysUser, sysUser1);
            sysUser.setPwdDomainCode(sysUser.getPassword());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            sysUser.setUpdateId(userId);
            sysUser.setUpdateTime(new Date());
            baseMapper.updateById(sysUser);

            // 删除角色，新增新的
            LambdaUpdateWrapper<SysRoleUser> userLambdaUpdateWrapper = new LambdaUpdateWrapper<SysRoleUser>();
            userLambdaUpdateWrapper.eq(SysRoleUser::getDisabled, 0);
            userLambdaUpdateWrapper.eq(SysRoleUser::getUserId, sysUser.getId());
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUpdateId(userId);
            sysRoleUser.setUpdateTime(new Date());
            sysRoleUser.setDisabled(1);
            sysRoleUserService.update(sysRoleUser, userLambdaUpdateWrapper);

            if (StringUtils.isNotEmpty(sysUser.getRoleId())) {
                String[] roleIdArr = sysUser.getRoleId().split(",");
                for (String roleId : roleIdArr) {
                    SysRoleUser sysRoleUser1 = new SysRoleUser();
                    sysRoleUser1.setRoleId(roleId);
                    sysRoleUser1.setUserId(sysUser.getId());
                    sysRoleUser1.setCreaterId(userId);
                    sysRoleUser1.setCreateTime(new Date());
                    sysRoleUser1.setUpdateId(userId);
                    sysRoleUser1.setUpdateTime(new Date());
                    sysRoleUserService.save(sysRoleUser1);
                }
            }

            //先删除用户组织关联表后再保存数据
            LambdaUpdateWrapper<SysUserOrg> orgWrapper = new LambdaUpdateWrapper<SysUserOrg>();
            orgWrapper.eq(SysUserOrg::getDisabled, 0);
            orgWrapper.eq(SysUserOrg::getUserId, sysUser.getId());
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setUpdateId(sysUser.getUpdateId());
            sysUserOrg.setUpdateTime(new Date());
            sysUserOrg.setDisabled(1);
            sysUserOrgService.update(sysUserOrg, orgWrapper);
            //新增用户组织关联表
            if(StringUtils.isNotEmpty(sysUser.getOrgId())){
                SysUserOrg sysUserOrg1 = new SysUserOrg();
                sysUserOrg1.setOrgId(sysUser.getOrgId());
                sysUserOrg1.setUserId(sysUser.getId());
                sysUserOrg1.setCreaterId(sysUser.getUpdateId());
                sysUserOrg1.setCreateTime(new Date());
                sysUserOrg1.setUpdateId(sysUser.getUpdateId());
                sysUserOrg1.setUpdateTime(new Date());
                sysUserOrgService.save(sysUserOrg1);
            }

            //先删除用户岗位关联表后再保存数据
            LambdaUpdateWrapper<SysUserPost> postWrapper = new LambdaUpdateWrapper<SysUserPost>();
            postWrapper.eq(SysUserPost::getDisabled, 0);
            postWrapper.eq(SysUserPost::getUserId, sysUser.getId());
            SysUserPost sysUserPost = new SysUserPost();
            sysUserPost.setUpdateId(sysUser.getUpdateId());
            sysUserPost.setUpdateTime(new Date());
            sysUserPost.setDisabled(1);
            sysUserPostService.update(sysUserPost, postWrapper);
            //新增用户岗位关联表
            if(StringUtils.isNotEmpty(sysUser.getPostId())){
                SysUserPost sysUserPost1 = new SysUserPost();
                sysUserPost1.setPostId(sysUser.getPostId());
                sysUserPost1.setUserId(sysUser.getId());
                sysUserPost1.setCreaterId(sysUser.getUpdateId());
                sysUserPost1.setCreateTime(new Date());
                sysUserPost1.setUpdateId(sysUser.getUpdateId());
                sysUserPost1.setUpdateTime(new Date());
                sysUserPost1.setTenantCode(sysUser.getTenantCode());
                sysUserPostService.save(sysUserPost1);
            }


        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public Integer feignAdd(SysUser sysUser){
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysUser::getLoginId, sysUser.getLoginId());
        qw.eq(SysUser::getDisabled, 0);
        List<SysUser> sysUsers = baseMapper.selectList(qw);
        if (null == sysUser.getId()) {

            if (CollectionUtils.isNotEmpty(sysUsers)) {
                return 1;
            }
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPwdDomainCode(sysUser.getPassword());
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateTime(new Date());
            baseMapper.insert(sysUser);
            //新增用户组织关联表
            if(StringUtils.isNotEmpty(sysUser.getOrgId())){
                SysUserOrg sysUserOrg = new SysUserOrg();
                sysUserOrg.setOrgId(sysUser.getOrgId());
                sysUserOrg.setUserId(sysUser.getId());
                sysUserOrg.setCreaterId(sysUser.getCreaterId());
                sysUserOrg.setCreateTime(new Date());
                sysUserOrg.setUpdateId(sysUser.getUpdateId());
                sysUserOrg.setUpdateTime(new Date());
                sysUserOrgService.save(sysUserOrg);
            }

            //新增用户岗位关联表
            if(StringUtils.isNotEmpty(sysUser.getPostId())){
                SysUserPost sysUserPost = new SysUserPost();
                sysUserPost.setPostId(sysUser.getPostId());
                sysUserPost.setUserId(sysUser.getId());
                sysUserPost.setCreaterId(sysUser.getCreaterId());
                sysUserPost.setCreateTime(new Date());
                sysUserPost.setUpdateId(sysUser.getUpdateId());
                sysUserPost.setUpdateTime(new Date());
                sysUserPost.setTenantCode(sysUser.getTenantCode());
                sysUserPostService.save(sysUserPost);
            }

            if (StringUtils.isNotEmpty(sysUser.getRoleId())) {
                String[] roleIdArr = sysUser.getRoleId().split(",");
                for (String roleId : roleIdArr) {
                    SysRoleUser sysRoleUser = new SysRoleUser();
                    sysRoleUser.setRoleId(roleId);
                    sysRoleUser.setUserId(sysUser.getId());
                    sysRoleUser.setCreaterId(sysUser.getCreaterId());
                    sysRoleUser.setCreateTime(new Date());
                    sysRoleUser.setUpdateId(sysUser.getUpdateId());
                    sysRoleUser.setUpdateTime(new Date());
                    sysRoleUserService.save(sysRoleUser);
                }
            }
        } else {
            SysUser sysUser1 = baseMapper.selectById(sysUser.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysUser, sysUser1);
            sysUser.setPwdDomainCode(sysUser.getPassword());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            sysUser.setUpdateTime(new Date());
            baseMapper.updateById(sysUser);

            // 删除角色，新增新的
            LambdaUpdateWrapper<SysRoleUser> userLambdaUpdateWrapper = new LambdaUpdateWrapper<SysRoleUser>();
            userLambdaUpdateWrapper.eq(SysRoleUser::getDisabled, 0);
            userLambdaUpdateWrapper.eq(SysRoleUser::getUserId, sysUser.getId());
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUpdateId(sysUser.getUpdateId());
            sysRoleUser.setUpdateTime(new Date());
            sysRoleUser.setDisabled(1);
            sysRoleUserService.update(sysRoleUser, userLambdaUpdateWrapper);

            if (StringUtils.isNotEmpty(sysUser.getRoleId())) {
                String[] roleIdArr = sysUser.getRoleId().split(",");
                for (String roleId : roleIdArr) {
                    SysRoleUser sysRoleUser1 = new SysRoleUser();
                    sysRoleUser1.setRoleId(roleId);
                    sysRoleUser1.setUserId(sysUser.getId());
                    sysRoleUser1.setCreaterId(sysUser.getUpdateId());
                    sysRoleUser1.setCreateTime(new Date());
                    sysRoleUser1.setUpdateId(sysUser.getUpdateId());
                    sysRoleUser1.setUpdateTime(new Date());
                    sysRoleUserService.save(sysRoleUser1);
                }
            }

            //先删除用户组织关联表后再保存数据
            LambdaUpdateWrapper<SysUserOrg> orgWrapper = new LambdaUpdateWrapper<SysUserOrg>();
            orgWrapper.eq(SysUserOrg::getDisabled, 0);
            orgWrapper.eq(SysUserOrg::getUserId, sysUser.getId());
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setUpdateId(sysUser.getUpdateId());
            sysUserOrg.setUpdateTime(new Date());
            sysUserOrg.setDisabled(1);
            sysUserOrgService.update(sysUserOrg, orgWrapper);
            //新增用户组织关联表
            if(StringUtils.isNotEmpty(sysUser.getOrgId())){
                SysUserOrg sysUserOrg1 = new SysUserOrg();
                sysUserOrg1.setOrgId(sysUser.getOrgId());
                sysUserOrg1.setUserId(sysUser.getId());
                sysUserOrg1.setCreaterId(sysUser.getUpdateId());
                sysUserOrg1.setCreateTime(new Date());
                sysUserOrg1.setUpdateId(sysUser.getUpdateId());
                sysUserOrg1.setUpdateTime(new Date());
                sysUserOrgService.save(sysUserOrg1);
            }

            //先删除用户岗位关联表后再保存数据
            LambdaUpdateWrapper<SysUserPost> postWrapper = new LambdaUpdateWrapper<SysUserPost>();
            postWrapper.eq(SysUserPost::getDisabled, 0);
            postWrapper.eq(SysUserPost::getUserId, sysUser.getId());
            SysUserPost sysUserPost = new SysUserPost();
            sysUserPost.setUpdateId(sysUser.getUpdateId());
            sysUserPost.setUpdateTime(new Date());
            sysUserPost.setDisabled(1);
            sysUserPostService.update(sysUserPost, postWrapper);
            //新增用户岗位关联表
            if(StringUtils.isNotEmpty(sysUser.getPostId())){
                SysUserPost sysUserPost1 = new SysUserPost();
                sysUserPost1.setPostId(sysUser.getPostId());
                sysUserPost1.setUserId(sysUser.getId());
                sysUserPost1.setCreaterId(sysUser.getUpdateId());
                sysUserPost1.setCreateTime(new Date());
                sysUserPost1.setUpdateId(sysUser.getUpdateId());
                sysUserPost1.setUpdateTime(new Date());
                sysUserPost1.setTenantCode(sysUser.getTenantCode());
                sysUserPostService.save(sysUserPost1);
            }

        }
        return 1;
    }

    @Override
    public Integer delete(String id) {
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = baseMapper.selectById(id);
        sysUser.setDisabled(1);
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        LambdaQueryWrapper<SysRoleUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRoleUser::getUserId, id);
        List<SysRoleUser> sysRoleUsers = sysRoleUserService.list(qw);
        LambdaQueryWrapper<SysUserOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserOrg::getUserId, id);
        List<SysUserOrg> sysUserOrgs = sysUserOrgService.list(wrapper);
        for (SysRoleUser sysRoleUser : sysRoleUsers) {
            sysRoleUser.setDisabled(1);
            sysRoleUser.setUpdateId(userId);
            sysRoleUser.setUpdateTime(new Date());
            sysRoleUserService.updateById(sysRoleUser);
        }
        for (SysUserOrg sysUserOrg : sysUserOrgs) {
            sysUserOrg.setDisabled(1);
            sysUserOrg.setUpdateId(userId);
            sysUserOrg.setUpdateTime(new Date());
            sysUserOrgService.updateById(sysUserOrg);
        }
        //删除用户岗位关联表
        LambdaUpdateWrapper<SysUserPost> postWrapper = new LambdaUpdateWrapper<SysUserPost>();
        postWrapper.eq(SysUserPost::getDisabled, 0);
        postWrapper.eq(SysUserPost::getUserId, sysUser.getId());
        SysUserPost sysUserPost = new SysUserPost();
        sysUserPost.setUpdateId(userId);
        sysUserPost.setUpdateTime(new Date());
        sysUserPost.setDisabled(1);
        sysUserPostService.update(sysUserPost, postWrapper);


        return 1;
    }

    @Override
    public Integer feignDelete(String id,String userId) {
        SysUser sysUser = baseMapper.selectById(id);
        sysUser.setDisabled(1);
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        LambdaQueryWrapper<SysRoleUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRoleUser::getUserId, id);
        List<SysRoleUser> sysRoleUsers = sysRoleUserService.list(qw);
        LambdaQueryWrapper<SysUserOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserOrg::getUserId, id);
        List<SysUserOrg> sysUserOrgs = sysUserOrgService.list(wrapper);
        for (SysRoleUser sysRoleUser : sysRoleUsers) {
            sysRoleUser.setDisabled(1);
            sysRoleUser.setUpdateId(userId);
            sysRoleUser.setUpdateTime(new Date());
            sysRoleUserService.updateById(sysRoleUser);
        }
        for (SysUserOrg sysUserOrg : sysUserOrgs) {
            sysUserOrg.setDisabled(1);
            sysUserOrg.setUpdateId(userId);
            sysUserOrg.setUpdateTime(new Date());
            sysUserOrgService.updateById(sysUserOrg);
        }

        //删除用户岗位关联表
        LambdaUpdateWrapper<SysUserPost> postWrapper = new LambdaUpdateWrapper<SysUserPost>();
        postWrapper.eq(SysUserPost::getDisabled, 0);
        postWrapper.eq(SysUserPost::getUserId, sysUser.getId());
        SysUserPost sysUserPost = new SysUserPost();
        sysUserPost.setUpdateId(userId);
        sysUserPost.setUpdateTime(new Date());
        sysUserPost.setDisabled(1);
        sysUserPostService.update(sysUserPost, postWrapper);

        return 1;
    }

    @Override
    public void configExpertQX(List<String> loginIds, List<String> delLoginIds, String tenantCode) {
        // 新建角色
        SysRole role = sysRoleService.dealExpertRole();
        // 角色项目
        sysRoleTenantService.inSertData(tenantCode, role.getId(), "sys");
        // 项目菜单
        // 角色菜单
        sysTenantPermissionService.dealExpertMenu(tenantCode, role.getId());
        // 人员角色
        for (String loginId : loginIds) {
            SysUser sysUser = this.queryByLoginId(loginId);
            sysRoleUserService.insertData(sysUser.getId(), role.getId(), "sys");
        }
        // 删除人员角色
        for (String loginId : delLoginIds) {
            SysUser sysUser = this.queryByLoginId(loginId);
            sysRoleUserService.deleteData(sysUser.getId(), role.getId(), "sys");
        }
    }

    @Override
    public List<String> getByLoginIds(List<String> loginIds) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDisabled, 0);
        queryWrapper.in(SysUser::getLoginId, loginIds);
        List<SysUser> sysUsers = baseMapper.selectList(queryWrapper);
        return sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
    }

    @Override
    public IPage<SysUser> getList(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = baseMapper.selectById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String userName = object.getString("userName");
        String userState = object.getString("userState");
        String orgId = object.getString("orgId");
        String roleId = object.getString("roleId");
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(userName)) {
            qw.like(SysUser::getUserName, userName);
        }
        if (StringUtils.isNotEmpty(userState)) {
            qw.eq(SysUser::getUserState, userState);
        }
        if (StringUtils.isNotEmpty(orgId)) {
            qw.inSql(SysUser::getId, "select user_id from sys_user_org where disabled=0 and org_id='"+orgId+"'");
        } else {
            // 如果不是超级管理员 只查询有权限查看的用户
            if (!"0".equals(sysUser.getIsStatus())) {
                qw.inSql(SysUser::getId, "SELECT DISTINCT a.user_id FROM sys_user_org a, sys_role_org c WHERE a.disabled = 0 AND c.disabled = 0 AND a.org_id = c.org_id AND c.role_id IN (SELECT role_id FROM sys_role_user WHERE disabled = 0 AND user_id = '"+userId+"')");
                qw.or().eq(SysUser::getCreaterId, userId);
            }
        }
        if (StringUtils.isNotEmpty(roleId)) {
            // 查询该角色配置的用户信息
            qw.inSql(SysUser::getId, "select user_id from sys_role_user where disabled = 0 and role_id = '"+roleId+"'");
        }

        qw.eq(SysUser::getDisabled, 0);
        qw.orderByDesc(SysUser::getUpdateTime);
        qw.eq(SysUser::getIsStatus, 1);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 500;
        }
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        IPage<SysUser> iPage = baseMapper.selectPage(page, qw);
        // 增加权限控制，只有本人或者创建人可以编辑修改删除(超管都可以操作)
        for (SysUser sysUser1 : iPage.getRecords()) {
            if ("0".equals(sysUser.getIsStatus()) || userId.equals(sysUser1.getId()) || userId.equals(sysUser1.getCreaterId())) {
                sysUser1.setEdit(true);
                sysUser1.setDel(true);
                sysUser1.setReset(true);
            } else {
                sysUser1.setEdit(false);
                sysUser1.setDel(false);
                sysUser1.setReset(false);
            }
            // 隐藏密码
            sysUser1.setPwdDomainCode("");
            sysUser1.setPassword("");
        }
        return iPage;
    }

    @Override
    public List<SysUser> getUserData(String userName) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysUser::getDisabled, 0);
        wrapper.eq(SysUser::getUserState, 2);
        wrapper.eq(SysUser::getIsStatus, 0);
        if (StringUtils.isNotEmpty(userName)) {
            wrapper.select(SysUser::getId, SysUser::getUserName);
        }
        List<SysUser> list = baseMapper.selectList(wrapper);
        return list;
    }

    @Override
    public List<String> getAllUserByTenantCode(String tenantCode) {
        List<String> stringList = new ArrayList<>();
        List<Map<String, Object>> list = baseMapper.getAllUserByTenantCode(tenantCode);
        for (Map<String, Object> temp : list) {
            stringList.add(MapUtils.getString(temp, "loginId", ""));
        }
        return stringList;
    }

    @Override
    public Integer passwordReset(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String password = object.getString("password");
        String id = object.getString("id");
        SysUser sysUser = baseMapper.selectById(id);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        sysUser.setPwdDomainCode(password);
        sysUser.setPassword(passwordEncoder.encode(password));
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        return 1;
    }


    @Override
    public void downloadTemplate(HttpServletResponse response, String tenantCode) {
//        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        String userId = RequestHeaderUtils.getUserId(request);

        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("人员导入");
        sheet.createFreezePane(1, 1);
        //设置基础样式
        Map<String, CellStyle> styleMap = ExcelUtil.createStylesTemplate(workbook);
        CellStyle headerStyle = styleMap.get("header");
        CellStyle dataStyle = styleMap.get("data");
        dataStyle.setDataFormat(workbook.createDataFormat().getFormat("@"));
        CellStyle requiredStyle = styleMap.get("required");

        //日期格式
        XSSFCellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setAlignment(HorizontalAlignment.CENTER);
        dateCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dateCellStyle.setBorderRight(BorderStyle.THIN);
        dateCellStyle.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        dateCellStyle.setBorderLeft(BorderStyle.THIN);
        dateCellStyle.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        dateCellStyle.setBorderTop(BorderStyle.THIN);
        dateCellStyle.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        dateCellStyle.setBorderBottom(BorderStyle.THIN);
        dateCellStyle.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = workbook.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        dateCellStyle.setFont(dataFont);
        short df=workbook.createDataFormat().getFormat("yyyy-mm-dd HH:mm:ss");
        dateCellStyle.setDataFormat(df);

        //数字格式
        DataFormat dfNum = workbook.createDataFormat();
        CellStyle numCellStyle = workbook.createCellStyle();
        numCellStyle.cloneStyleFrom(dataStyle);
        numCellStyle.setDataFormat(dfNum.getFormat("0.000"));

        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 设置第一行,表头
        Row titleRow = sheet.createRow(0);
        titleRow.setHeight((short) 350);

        String[] names = new String[] {"*组织","*登陆账号","*昵称","*密码","手机号","邮箱","*用户状态","角色","备注"};
        for (int i = 0; i < names.length; i++) {
            titleRow.createCell(i).setCellValue(names[i]);
            if (names[i].startsWith("*")) {
                titleRow.getCell(i).setCellStyle(requiredStyle);
            } else {
                titleRow.getCell(i).setCellStyle(headerStyle);
            }
        }
        // 设置单元格格式
        // 查询所属项目下包含的有权限查看的标段
        List<SysOrg> orgs = sysOrgService.getInfoByUserIdAndTenantCode(userId, tenantCode);

        // 标段
        String[] orgCodes = new String[orgs.size()];
        for (int i=0; i<orgs.size(); i++) {
            orgCodes[i] = orgs.get(i).getOrgName();
        }

//        orgCodes[0] = orgCode;
        ExcelUtil.setXSSFValidation(sheet, orgCodes, 1, 500, 0, 0);

        //赋值下拉框数据
        Map<String, Object> map = queryMaterialField(tenantCode, userId);
        if(!map.isEmpty()){
            //需要下拉的字段名称
            String[] fields= new String[]{"userState","roleIds"};
            //下拉框对应的列index
            int[] cols= new int[]{6,7};
            //sheet页存数据的列
            String[] arr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
            int index = 0;

            Sheet sheetHidden = workbook.createSheet("Sheet2");
            workbook.setSheetHidden(1, true);
            Row row;

            for (int k = 0; k < fields.length; k++) {
                List<String> codes = (List<String>) map.get(fields[k]);

                String[] codeArr = new String[codes.size()];
                for (int i = 0; i < codes.size(); i++) {
                    codeArr[i] = codes.get(i);
                }

                //String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据
                String strFormula = "Sheet2!$" + arr[index] + "$1:$" + arr[index] + "$" + codeArr.length; //Sheet2第A1到A5000作为下拉列表来源数据

                sheet.addValidationData(setMoreDataValidation(workbook, sheet, strFormula,1, 500,cols[k], cols[k])); //下拉列表元素很多的情况
                //2、生成sheet2内容
                for (int j = 0; j < codeArr.length; j++) {
                    if (index == 0) { //第1个下拉选项，直接创建行、列
                        row = sheetHidden.createRow(j); //创建数据行
                        //      sheetHidden.setColumnWidth(j, 4000); //设置每列的列宽
                        row.createCell(0).setCellValue(codeArr[j]); //设置对应单元格的值
                    } else { //非第1个下拉选项
                        int rowCount = sheetHidden.getLastRowNum();
                        if (j <= rowCount) { //前面创建过的行，直接获取行，创建列
                            //获取行，创建列
                            sheetHidden.getRow(j).createCell(index).setCellValue(codeArr[j]); //设置对应单元格的值
                        } else { //未创建过的行，直接创建行、创建列
                            //  sheetHidden.setColumnWidth(j, 4000); //设置每列的列宽
                            //创建行、创建列
                            sheetHidden.createRow(j).createCell(index).setCellValue(codeArr[j]); //设置对应单元格的值
                        }
                    }
                }
                index++;
            }

        }

        String name = "人员导入模板_" + DateUtils.formatYMDHMS(new Date());
        //下载
        FileUtil.downloadExcel(name, response, workbook);
    }

    private Map<String, Object> queryMaterialField(String tenantCode, String userId) {
        Map<String, Object> result = new HashMap<>();

        //查询用户拥有权限的标段
        List<String> orgCodes = new ArrayList<>();
        List<SysOrg> sysOrgs = sysOrgService.getInfoByUserIdAndTenantCode(userId, tenantCode);
        for (SysOrg sysOrg : sysOrgs) {
            orgCodes.add(sysOrg.getOrgCode());
        }

        Map<String,Object> params = new HashMap<>();
        params.put("tenantCode",tenantCode);
        params.put("orgCodes",orgCodes);
        params.put("userId",userId);

        //1用户状态  2角色
        String[] names= new String[]{"userState","roleIds"};
        for (int i = 0; i < 2; i++) {
            params.put("type",i+1);
            if(params.get("type").equals(1)){
                List<String> materialBaseInfos = baseMapper.queryDistinctField(params);
                result.put(names[i],materialBaseInfos);
            }else if(params.get("type").equals(2)){
                List<String> materialBaseInfos = baseMapper.selectRoleList1(params);
                result.put(names[i],materialBaseInfos);
            }
        }
        return result;
    }

    private static DataValidation setMoreDataValidation(Workbook wb, Sheet sheet, String strFormula, int startRow, int endRow, int startColumn, int endColumn) {

        DataValidation dataValidation;
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(startRow, endRow, startColumn, endColumn);
        if (wb instanceof XSSFWorkbook) {
            //获取新sheet页内容
            XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST, strFormula);
            // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
            // 数据有效性对象
            DataValidationHelper help = new XSSFDataValidationHelper((XSSFSheet) sheet);
            dataValidation = help.createValidation(constraint, regions);
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            // 设置数据有效性加载在哪个单元格上。四个参数分别是：起始行、终止行、起始列、终止列
            DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula);
            dataValidation = new HSSFDataValidation(regions, constraint);
            dataValidation.setSuppressDropDownArrow(false);
        }
        dataValidation.setEmptyCellAllowed(true);
        dataValidation.setShowPromptBox(true);
        dataValidation.createErrorBox("Error", "请选择下拉框中的数据");
        dataValidation.createPromptBox("提示", "只能选择下拉框里面的数据");
        return dataValidation;

    }

    @Override
    public Map<String, Object> importExcel(MultipartFile uploadFile, String tenantCode) {
//        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        String userId = RequestHeaderUtils.getUserId(request);
        Map<String, Object> ret = new HashMap<>();
        List<String> errorMsg = new ArrayList<>();
        // 验证模板是否正确
        int sucess = 0;
        try {
            request.setCharacterEncoding("utf-8");
            Map<Integer, ReadExcleDefine> maps = new HashMap<Integer, ReadExcleDefine>();
            String[] names = new String[] {"*组织","*登陆账号","*昵称","*密码","手机号","邮箱","*用户状态","角色","备注"};
            for (int i=0; i<names.length; i++) {
                ReadExcleDefine redefine = new ReadExcleDefine(names[i], true,"String", 100, null);
                maps.put(i+1, redefine);
            }
            // 读入excle
            ReadXSSExcelUtil readExcel = new ReadXSSExcelUtil(maps, uploadFile);
            // 总行数
            int count = readExcel.getRowCount();
            if (count > 500) {
                errorMsg.add("导入最大行数为500，请修改后重新导入！");
                ret.put("errorMsg", errorMsg);
                return ret;
            }
            // 标段权限校验
            List<SysOrg> orgCodes = sysOrgService.getInfoByUserIdAndTenantCode(userId,tenantCode);
            // 角色权限校验
            List<SysRole> sysRoles = sysRoleService.getRoleListByTenantCode(tenantCode);

            for (int i = 1; i <= count; i++) {
                String[] rows = readExcel.readExcelLine(i);
                // 获取+验证单元格信息
                if (rows == null || "".equals(rows[0])) {
                    continue;
                }
                // 开始处理数据
                List<String> errorMsgCheck = this.checkDataAndSave(rows, i+1, orgCodes, sysRoles);
                if (!CollectionUtils.isEmpty(errorMsgCheck)) {
                    errorMsg.addAll(errorMsgCheck);
                } else {
                    sucess += 1;
                }
            }

        }catch (Exception e) {
            errorMsg.add("系统错误，请确认模板是否正确！");
            e.printStackTrace();
        }
        ret.put("success", sucess);
        ret.put("errorMsg", errorMsg);
        return ret;
    }

    @Override
    public String addUserByZhgd(String inParam) {

        JSONObject object = JSONObject.parseObject(inParam);
        String loginIdOld = object.getString("loginIdOld");
        String loginId = object.getString("loginId");
        String userName = object.getString("userName");
        String userId = object.getString("userId");

        String tenantCode = object.getString("tenantCode");
        String orgCode = object.getString("orgCode");

        String sysUserId = "";

        if (StringUtils.isEmpty(loginId)) {
            loginId = PinYinUtil.getPinyin(userName);
        }

        // 查询是否已存在
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysUser::getLoginId, loginId);
        qw.eq(SysUser::getDisabled, 0);
        qw.last(" limit 1");
        SysUser sysUsers = baseMapper.selectOne(qw);
        if (null == sysUsers) {
            boolean insertFlag = true;
            // 如果已存在老的，直接原基础更新，否则新增
            if (StringUtils.isNotEmpty(loginIdOld)) {
                LambdaQueryWrapper<SysUser> qwO = new LambdaQueryWrapper<>();
                qwO.eq(SysUser::getLoginId, loginIdOld);
                qwO.eq(SysUser::getDisabled, 0);
                qwO.last(" limit 1");
                SysUser sysUsersO = baseMapper.selectOne(qwO);
                if (null != sysUsersO) {
                    insertFlag = false;
                    sysUserId = sysUsersO.getId();

                    sysUsersO.setLoginId(loginId);
                    sysUsersO.setUserName(userName);
                    sysUsersO.setUpdateTime(new Date());
                    sysUsersO.setUpdateId(userId);
                    baseMapper.updateById(sysUsersO);

                }
            }
            if (insertFlag) {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                SysUser sysUser = new SysUser();
                sysUser.setLoginId(loginId);
                sysUser.setMobile(loginId);
                sysUser.setUserName(userName);
                String passwordD = PinYinUtil.getPinyin(userName);
                sysUser.setPwdDomainCode(passwordD);
                sysUser.setPassword(passwordEncoder.encode(passwordD));
                sysUser.setUserState(1);
                sysUser.setCreaterId(userId);
                sysUser.setCreateTime(new Date());
                sysUser.setUpdateId(userId);
                sysUser.setUpdateTime(new Date());
                baseMapper.insert(sysUser);

                sysUserId = sysUser.getId();
            }
        } else {
            sysUserId = sysUsers.getId();
            // 直接更新名称
            sysUsers.setUserName(userName);
            sysUsers.setUpdateTime(new Date());
            sysUsers.setUpdateId(userId);
            baseMapper.updateById(sysUsers);
        }

        // 查询组织id
        if (StringUtils.isNotEmpty(sysUserId) && StringUtils.isNotEmpty(tenantCode) && StringUtils.isNotEmpty(orgCode)) {
            LambdaQueryWrapper<SysOrg> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysOrg::getDisabled, 0);
            queryWrapper1.eq(SysOrg::getOrgCode, orgCode);
            queryWrapper1.eq(SysOrg::getTenantCode, tenantCode);
            queryWrapper1.last(" limit 1");
            SysOrg sysOrg = sysOrgService.getOne(queryWrapper1);
            if (null != sysOrg) {
                // 查询关系是否已配置
                LambdaQueryWrapper<SysUserOrg> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(SysUserOrg::getDisabled, 0);
                queryWrapper2.eq(SysUserOrg::getOrgId, sysOrg.getId());
                queryWrapper2.eq(SysUserOrg::getUserId, sysUserId);
                queryWrapper2.last(" limit 1");
                SysUserOrg sysUserOrg = sysUserOrgService.getOne(queryWrapper2);
                if (null == sysUserOrg) {
                    SysUserOrg insert = new SysUserOrg();
                    insert.setUserId(sysUserId);
                    insert.setOrgId(sysOrg.getId());
                    insert.setCreaterId(userId);
                    insert.setCreateTime(new Date());
                    insert.setUpdateId(userId);
                    insert.setUpdateTime(new Date());
                    sysUserOrgService.save(insert);
                }
            }
        }
        return sysUserId;
    }

    @Override
    public SysUser verificatLoginIdAndPasswrod(String loginId, String password) {
        //查询loginId对应的用户数据
        SysUser sysUser = queryByLoginId(loginId);
        if(sysUser==null){
            return null;
        }
        String passwordO = sysUser.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(passwordEncoder.matches(password,passwordO)){
            return sysUser;
        }

        return null;
    }

    @Override
    public Boolean getSuperUserFlag() {
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = baseMapper.selectById(userId);
        if (null != sysUser && "0".equals(sysUser.getIsStatus())) {
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getUser() {
        String tenantCode = RequestHeaderUtils.getTenantCode(request);

        return baseMapper.getUser(tenantCode);
    }

    @Override
    public SysUser getDetail(String userId) {
        SysUser sysUser = baseMapper.selectById(userId);
        // 查询角色id
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getDisabled, 0);
        queryWrapper.eq(SysRoleUser::getUserId, userId);
        List<SysRoleUser> list = sysRoleUserService.list(queryWrapper);

        if (CollectionUtils.isNotEmpty(list)) {
            StringBuilder buf = new StringBuilder();
            for (SysRoleUser sysRoleUser : list) {
                buf.append(sysRoleUser.getRoleId()).append(",");
            }
            sysUser.setRoleId(buf.substring(0, buf.length()-1));
        }
        return sysUser;
    }

    @Override
    public List<SysUser> queryUsersByGroupIds(List<String> groupIdList) {
        return baseMapper.queryUsersByGroupIds(groupIdList);
    }

    @Override
    public List<SysUser> queryUsersByTenantCode(String tenantCode) {
        return baseMapper.queryUsersByTenantCode(tenantCode);
    }

    @Override
    public List<SysUser> queryUsersByTenantAndOrg(String tenantCode, String orgCode) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDisabled, 0);
        lambdaQueryWrapper.eq(SysUser::getIsStatus, 1);
        lambdaQueryWrapper.inSql(SysUser::getId, "select a.user_id from sys_user_org a, sys_org b where a.disabled=0 and b.disabled=0 " +
                "and a.org_id=b.id and b.org_code='"+orgCode+"' and b.tenant_code='"+tenantCode+"'");
        return baseMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public IPage<Map<String, Object>> getUserListPage(HttpServletRequest request, String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String userName = object.getString("userName");
        String tenantCode = object.getString("tenantCode");
        String orgCode = object.getString("orgCode");
        /**
         * 分页条件
         */
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<Map<String,Object>> page = new Page<>(pageNum, pageSize);

        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("userName",userName);
        params.put("tenantCode",tenantCode);
        params.put("orgCode",orgCode);
        IPage<Map<String,Object>> pages = baseMapper.getUserListPage(page,params);
        if(pages!=null && pages.getRecords()!=null && pages.getRecords().size()>0){
            for(Map<String,Object> sysUser:pages.getRecords()){
                sysUser.put("password","******");
                //根据项目、标段、用户查询角色列表
                String proCode = MapUtils.getString(sysUser,"tenantCode","");
                String orgId = MapUtils.getString(sysUser,"orgId","");
                String uId = MapUtils.getString(sysUser,"id","");
                Map<String,Object> roleMap = sysRoleService.queryRoleByProSecUser(proCode,orgId,uId);
            }
        }
        return pages;
    }

    @Override
    public List<Map<String, Object>> getUsersByTenantCodeAndOrgCode(String tenantCode, String orgCode) {
        return baseMapper.getUsersByTenantCodeAndOrgCode(tenantCode, orgCode);
    }

    private List<String> checkDataAndSave(String[] rows, int rowNum, List<SysOrg> orgCodes, List<SysRole> sysRoles) throws Exception {
        List<String> errorMsg = new ArrayList<>();
        // 校验必填
        String[] names = new String[] {"*组织","*登陆账号","*昵称","*密码","手机号","邮箱","*用户状态","角色","备注"};
        for (int j=0; j<names.length; j++) {
            if (names[j].startsWith("*") && StringUtils.isEmpty(rows[j])) {
                errorMsg.add("第"+rowNum+"行：必填项不能为空！");
                return errorMsg;
            }
        }
        // 列出所有字段
        String orgName = rows[0];
        String loginId = rows[1];
        String userName = rows[2];
        String password = rows[3];
        String mobile = rows[4];
        String email = rows[5];
        String userState = rows[6];
        String roleName = rows[7];
        String remark = rows[8];

        // 校验标段是否存在
        SysUser sysUser = new SysUser();

        if (StringUtils.isNotEmpty(orgName)) {
            for (SysOrg sysOrg : orgCodes) {
                if (orgName.equals(sysOrg.getOrgName())) {
                    sysUser.setOrgId(sysOrg.getId());
                    break;
                }
            }
            if (StringUtils.isEmpty(sysUser.getOrgId())) {
                errorMsg.add("第"+rowNum+"行：组织不存在！");
                return errorMsg;
            }
        }
        // 校验角色是否合法
        if (StringUtils.isNotEmpty(roleName)) {
            for (SysRole sysRole : sysRoles) {
                if (roleName.equals(sysRole.getRoleName())) {
                    sysUser.setRoleId(sysRole.getId());
                    break;
                }
            }
            if (StringUtils.isEmpty(sysUser.getRoleId())) {
                errorMsg.add("第"+rowNum+"行：角色不存在！");
                return errorMsg;
            }
        }

        // 校验数据合法
        // 开始入库校验
        sysUser.setLoginId(loginId);
        sysUser.setUserName(userName);
        sysUser.setPassword(password);
        sysUser.setMobile(mobile);
        sysUser.setEmail(email);
        if(userState.equals("未激活")){
            sysUser.setUserState(1);
        }else {
            sysUser.setUserState(2);
        }
        sysUser.setRemark(remark);
        ResultBean<String> resultBean = this.add(sysUser);
        if (resultBean.getCode() != 200) {
            errorMsg.add("第"+rowNum+"行：" + resultBean.getMsg());
            return errorMsg;
        }
        return null;
    }


    @Override
    public List<Map<String, Object>> getUserListByTenantCodeAndOrgCode(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);
        JSONObject object = JSONObject.parseObject(inParam);
        String tenantCode = object.getString("proCode");
        String orgCode = object.getString("orgCode");
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("tenantCode",tenantCode);
        params.put("orgCode",orgCode);
        return baseMapper.getUserListByTenantCodeAndOrgCode(params);
    }

    @Override
    public List<Map<String, Object>> getUserListByTenantCodeAndOrgCodeSuper(String inParam) {
        String userId = RequestHeaderUtils.getUserId(request);

        JSONObject object = JSONObject.parseObject(inParam);
        String tenantCode = object.getString("proCode");
        String orgCode = object.getString("orgCode");
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("orgCode",orgCode);

        StringJoiner tenantCodes = new StringJoiner(",");
        List<SysProject> sysProjectList = sysProjectService.getProjectInfoByUserId(userId);
        if(StringUtils.isNotEmpty(tenantCode)){
            tenantCodes.add("'"+tenantCode+"'");
        }else{
            for (SysProject sysProject : sysProjectList) {
                tenantCodes.add("'"+sysProject.getTenantCode()+"'");
            }
        }

        params.put("tenantCodes",tenantCodes.toString());

        return baseMapper.getUserListByTenantCodeAndOrgCodeSuper(params);
    }

    @Override
    public List<SysUser> getByRoleCode(String roleCode) {
        return baseMapper.getByRoleCode(roleCode);
    }

    @Override
    public String getUserOrgInfoByUserId(String userId, String tenantCode) {

        return baseMapper.getUserOrgInfoByUserId(userId, tenantCode);
    }
}
